<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/2/20
 * Time: 16:46
 */

namespace app\admin\controller;


use think\Db;
use think\Request;

class Member extends Base
{
    /**
     * 用户列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax()){
            $where['user_status'] = ['neq', 3];
            $where['user_private_worker'] = 1;
//            $where['user_private_worker'] = 1;
            $keyword = trim(input('keyword'), ' '); // 用户ID/手机号/姓名/昵称
            $user_gender = input('user_gender'); // 性别   1 男   2 女   3 未知
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $user_bo_role = input('user_bo_role'); // 1 普通用户  2 自由创业者  3 团员   4 团队长
            $user_bo_district_role = input('user_bo_district_role'); // 2 县级运营商  3 市级分公司  4 省级子公司
            $start_time = input('start_time'); // 注册开始时间
            $end_time = input('end_time'); // 注册结束时间
            $login_start_time = input('login_start_time'); // 登录开始时间
            $login_end_time = input('login_end_time'); // 登录结束时间
            $user_rule = input('user_rule'); // 1 普通用户  2 特惠商品  3 脖脸皮  2,3特惠商品&脖脸皮
            $th_rule = input('th_rule'); // 特惠礼包权限
            // 关键字
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|user_real_name'] = ['like', '%' . $keyword . '%'];
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['user_gender'] = $user_gender;
            }
            // 省
            if(isset($user_sheng) && $user_sheng != ''){
                $where['user_sheng'] = $user_sheng;
            }
            // 市
            if(isset($user_shi) && $user_shi != ''){
                $where['user_shi'] = $user_shi;
            }
            // 区
            if(isset($user_qu) && $user_qu != ''){
                $where['user_qu'] = $user_qu;
            }
            // 脖脸皮系统等级
            if(isset($user_bo_role) && $user_bo_role != ''){
                $where['user_bo_role'] = $user_bo_role;
            }
            // 脖脸皮地区等级
            if(isset($user_bo_district_role) && $user_bo_district_role != ''){
                $where['user_bo_district_role'] = ['LIKE', '%,' . $user_bo_district_role . ',%'];
            }
            // 类型
            if(isset($user_rule) && $user_rule != ''){
                if($user_rule == 1){
                    $where['user_rule'] = 1;
                }elseif ($user_rule == 2){
                    $where['user_rule'] = [['=', 2], ['=', '2,3'], 'OR'];
                }elseif ($user_rule == 3){
                    $where['user_rule'] = [['=', 3], ['=', '2,3'], 'OR'];
                }else{
                    $where['user_rule'] = '2,3';
                }
            }
            // 特惠礼包权限
            if(isset($th_rule) && $th_rule != ''){
                $where['user_th_rule'] = $th_rule;
            }
            // 注册时间
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['user_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['<=', $end_time];
            }
            // 登录时间
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['between', [$login_start_time, $login_end_time]];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time == ''){
                $where['user_last_login'] = ['>=', $login_start_time];
            }
            if(isset($login_start_time) && $login_start_time == '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['<=', $login_end_time];
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('u_user')
                ->join('up_th_rule', 'rule_id = user_th_rule', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('u_user')
                ->join('up_th_rule', 'rule_id = user_th_rule', 'LEFT')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('user_status asc, user_time desc')
                ->select();
            $store = Db::table('up_bo_giftbag_store')->column('bs_user_id');
            foreach ($lists as $k => $v){
                $lists[$k]['have_store'] = 2; // 没有店铺
                if($store){
                    foreach ($store as $ke => $vo){
                        if($vo == $v['user_id']){
                            $lists[$k]['have_store'] = 1; // 有店铺
                        }
                    }
                }
                // 代理身份
                if($v['user_bo_district_role'] == 1){
                    $district_role = '普通用户';
                    $lists[$k]['district_role'] = $district_role;
                }else{
                    $district_role = '';
                    if(strpos($v['user_bo_district_role'], ',2,') !== false) $district_role .= '县级运营商';
                    if(strpos($v['user_bo_district_role'], ',3,') !== false) $district_role .= '，市级分公司';
                    if(strpos($v['user_bo_district_role'], ',4,') !== false) $district_role .= '，省级子公司';
                    $lists[$k]['district_role'] = trim($district_role, '，');
                }

            }
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $thRule = Db::table('up_th_rule')->where('rule_status', 1)->field('rule_id, rule_name')->select();
        $this->assign([
            'province' => $province,
            'rule' => $thRule
        ]);
        return $this->fetch();
    }
    
    /**
     * 查询权限
     * @return \think\response\Json
     */
    public function user_index(){
        $user_id = input('id');
        $value = input('num');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_index', $value);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 报备权限
     * @return \think\response\Json
     */
    public function user_submit(){
        $user_id = input('id');
        $value = input('num');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_submit', $value);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 设置老师
     * @return \think\response\Json
     */
    public function user_teacher(){
        $user_id = input('id');
        $value = input('num');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_teacher', $value);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 冻结
     * @return \think\response\Json
     */
    public function down(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 2);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 启用
     * @return \think\response\Json
     */
    public function up(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 1);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 添加
     * @return mixed
     */
    public function memberAdd(){
        if(Request::instance()->isPost()){
            $user_username = trim(input('user_username'), ' ');
            $user_phone = input('user_phone');
            $user_image = input('user_image');
            $user_gender = input('user_gender');
            $user_status = input('user_status');
            $user_index = input('user_index');
            $user_submit = input('user_submit');
            $user_search = input('user_search');
            $user_password = input('user_password');
            if(!$user_username || !$user_phone || !$user_username || !$user_password){
                return json(['code' => 100, 'msg' => '有未填项']);
            }
            if(!preg_match("/^1[123456789]\d{9}$/", $user_phone)){
                return json(['code' => 100, 'msg' => '请填写正确的手机号']);
            }
            $today = date('Y-m-d H:i:s');
            $inivte_code = $this->getRandChar(8);
            
            $update = [
                'user_username' => $user_username,
                'user_phone' => $user_phone,
                'user_image' => $user_image,
                'user_gender' => $user_gender,
                'user_status' => $user_status,
                'user_index' => $user_index,
                'user_submit' => $user_submit,
                'user_search' => $user_search,
                'user_time' => $today,
                'user_update_time' => $today,
                'user_from' => 2,
                'user_invite' => $inivte_code,
                'user_invite_qrcode' => $this->getQrcode($inivte_code)
            ];
            $update['user_password'] = md5($user_password);
            $have = Db::table('up_u_user')
                ->where('user_phone', $user_phone)
                ->find();
            if($have){
                return json(['code' => 100, 'msg' => '此手机号码已经有了']);
            }
            $res = Db::table('up_u_user')->insert($update);
            if($res){
                return json(['code' => 200, 'msg' => '成功']);
            }else{
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        return $this->fetch('member/add');
    }

    /**
     * 编辑app用户
     * @return mixed|\think\response\Json
     */
    public function appMemberDetail(){
        $user_id = input('user_id');
        $user = Db::table('up_u_user')->where('user_id', $user_id)
            ->field('user_username, user_image, user_phone, user_gender, user_real_name, user_shop_name, 
            user_address, user_sheng, user_shi, user_qu, user_bank_username, 
            user_bank_name, user_bankcard_code, user_rule, user_status, user_index, user_submit, 
            user_search, user_bo_role, user_stock_role, user_giftbag_role, user_giftbag_level, user_invite, 
            user_bo_invite_other, user_shou_rule, user_serve_rule, user_fp_serve_rule, user_bo_district_role, user_dj_rule, 
            user_password_see, user_big_rule, user_system_show, user_giftbag_show, user_dl_show, user_th_rule')
            ->find();
        if(Request::instance()->isPost()){
            $user_image = input('user_image');
            $user_phone = trim(input('user_phone'));
            $user_password = input('user_password');
            $user_username = input('user_username');
            $user_gender = input('user_gender');
            $user_shop_name = input('user_shop_name');
//            $user_bo_role = input('user_bo_role');
            $user_stock_role = input('user_stock_role');
            $user_rule = input('user_rule/a');
            if($user_rule){
                $user_rule = implode(',', $user_rule);
            }else{
                $user_rule = '1';
            }
            $user_bo_district_role = input('user_bo_district_role/a');
            if($user_bo_district_role){
                $user_bo_district_role = implode(',', $user_bo_district_role);
            }else{
                $user_bo_district_role = '1';
            }
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $user_address = input('user_address');
            $user_bank_username = input('user_bank_username');
            $user_bank_name = input('user_bank_name');
            $user_bankcard_code = input('user_bankcard_code');
            $user_status = input('user_status');
            $user_index = input('user_index');
            $user_submit = input('user_submit');
            $user_search = input('user_search');
            $giftbag_role = input('giftbag_role');
            $user_giftbag_level = input('user_giftbag_level');
            $user_real_name = input('user_real_name');
            $user_shou_rule = input('user_shou_rule');
            $user_serve_rule = input('user_serve_rule');
            $user_fp_serve_rule = input('user_fp_serve_rule');
            $user_dj_rule = input('user_dj_rule');
            $user_big_rule = input('user_big_rule');
            $user_system_show = input('user_system_show');
            $user_giftbag_show = input('user_giftbag_show');
            $user_dl_show = input('user_dl_show');
            $user_th_rule = input('user_th_rule');
            $sheng_name = Db::table('up_area')->where('district_id', $user_sheng)->value('district');
            $shi_name = Db::table('up_area')->where('district_id', $user_shi)->value('district');
            $qu_name = Db::table('up_area')->where('district_id', $user_qu)->value('district');

            if(!preg_match("/^1[123456789]\d{9}$/", $user_phone)){
                return json(['code' => 100, 'msg' => '请填写正确的手机号']);
            }
            if($user['user_phone'] != $user_phone){
                $have = Db::table('up_u_user')
                    ->where('user_phone', $user_phone)
                    ->find();
                if($have){
                    return json(['code' => 100, 'msg' => '此手机号码已经有了']);
                }
            }

            // 是否有薄脸皮上级
            if($user_bo_district_role != '1'){
                if($user['user_invite'] != 'djl9988'){
                    if(!$user['user_bo_invite_other']){
                        return json(['code' => 100, 'msg' => '设置脖脸皮等级之前，请先绑定脖脸皮的上下级关系']);
                    }
                }
            }

            // 我的上级
            $upUser = Db::table('up_u_user')
                ->where('user_invite', $user['user_bo_invite_other'])
                ->field([
                    'user_id',
                    'user_bo_role',
                    'user_invite',
                    'user_tz_code',
                    'user_up_tz_code',
                    'user_up_up_tz_code'
                ])
                ->find();

            // 如果不是普通用户，则需要判断我的上级是否也是团员，
            // 如果我的上级也是不是团队长，则需要判断上级推广了几个非普通用户，达到2个，则需要将上级升级成团队长
            $can = 0;  // 上级是否要升级成团长  0 不升级  1 升级
            if($user_bo_district_role != '1'){ // 如果不是普通用户
                if($upUser['user_bo_role'] != 4){
                    $number = Db::table('up_u_user')
                        ->where([
                            'user_bo_invite_other' => $upUser['user_invite'],
                            'user_bo_role' => ['>', 2],
                            'user_id' => ['<>', $user_id]
                        ])
                        ->count();
                    if($number == 1){
                        $can = 1; // 可以升级成团长
                    }
                }
            }

            // 用户信息
            $update = [
                'user_real_name'     => $user_real_name,
                'user_phone'         => $user_phone,
                'user_username'      => $user_username,
                'user_gender'        => $user_gender,
                'user_shop_name'     => $user_shop_name,
//                'user_bo_role' => $user_bo_role,
                'user_rule'          => $user_rule,
                'user_sheng'         => $user_sheng,
                'user_shi'           => $user_shi,
                'user_qu'            => $user_qu,
                'user_area_str'      => $sheng_name . $shi_name . $qu_name,
                'user_address'       => $user_address,
                'user_bank_username' => $user_bank_username,
                'user_bank_name'     => $user_bank_name,
                'user_bankcard_code' => $user_bankcard_code,
                'user_update_time'   => date('Y-m-d H:i:s'),
                'user_status'        => $user_status,
                'user_index'         => $user_index,
                'user_submit'        => $user_submit,
                'user_search'        => $user_search,
                'user_stock_role'    => $user_stock_role,
//                'user_giftbag_role' => $giftbag_role,
                'user_giftbag_level' => $user_giftbag_level,
                'user_shou_rule'     => $user_shou_rule,
                'user_serve_rule'    => $user_serve_rule,
                'user_fp_serve_rule' => $user_fp_serve_rule,
                'user_dj_rule'       => $user_dj_rule,
                'user_big_rule'      => $user_big_rule,
                'user_system_show'   => $user_system_show,
                'user_giftbag_show'  => $user_giftbag_show,
                'user_dl_show'       => $user_dl_show,
                'user_th_rule'       => $user_th_rule
            ];

            if($user_bo_district_role != '1'){
                $user_bo_district_role = ',' . $user_bo_district_role . ',';
            }
            $update['user_bo_district_role'] = $user_bo_district_role;

            if(!empty($user_image)) $update['user_image'] = $user_image;
            if(!empty($user_password)){
                $update['user_password'] = md5($user_password);
                $update['user_password_see'] = $user_password;
            }

            // 如果我原来不是团长，现在成了代理，那需要改变我的身份，确定团队长编号等字段
            if($user['user_bo_role'] != 4 && $user_bo_district_role != '1'){
                $update['user_bo_role'] = 4; // 脖脸皮系统身份
                // 第一个未被使用的编号
                $code = $this->getFirstNoUseTzCode();
                $update['user_tz_code'] = $code['code']; // 团队长编号
//                $update['user_ty_code'] = 0;
                $_ty = $this->getTyCode($upUser['user_up_tz_code']);
                $update['user_ty_code'] = $_ty['user_ty_code'] + 1; // 团员编号
                if($user['user_bo_role'] != 3){ // 普通用户直接升团长
                    if($upUser['user_bo_role'] == 3){ // 如果上级是团员
                        $update['user_up_tz_code'] = $upUser['user_up_tz_code'];
                        $update['user_up_up_tz_code'] = $upUser['user_up_up_tz_code'];
                    }else{
                        $update['user_up_tz_code'] = $upUser['user_tz_code'];
                        $update['user_up_up_tz_code'] = $upUser['user_up_tz_code'];
                    }
                }
            }
            if(($user_rule == '3' || $user_rule == '2,3') && $user_giftbag_level == 3 && $user_bo_district_role == '1' && $user['user_bo_role'] == 1){
                $update['user_bo_role'] = 2; // 自由创业者
            }

            Db::startTrans();
            try{
                Db::table('up_u_user')->where('user_id', $user_id)->update($update);
                // 特惠商品商品收货地址
                if($user_sheng && $user_shi && $user_qu && $user_address){
                    $address = [
                        'addr_sheng' => $user_sheng,
                        'addr_shi' => $user_shi,
                        'addr_qu' => $user_qu,
                        'addr_address' => $user_address,
                        'addr_updatetime' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_user_address')->where(['addr_user_id' => $user_id, 'addr_from' => 1])->update($address);
                }

                // 升级上级为团队长
                if($can == 1){
                    // 第一个未被使用的编号
                    $upCode = $this->getFirstNoUseTzCode();
                    $upTzCode = $upCode['code']; // 团队长编号
                    $upUserUpdate = [
                        'user_id' => $upUser['user_id'],
                        'user_bo_role' => 4,
                        'user_tz_code' => $upTzCode,
//                        'user_ty_code' => 0,
                        'user_update_time' => date('Y-m-d H:i:s')
                    ];
                    Db::table('up_u_user')->update($upUserUpdate);
                }

                Db::commit();
                $result = 1;
                $msg = '编辑成功';
            }catch(\Exception $e){
                Db::rollback();
                $result = 2;
                $msg = $e->getMessage();
            }
            if($result == 1){
                if(($user['user_rule'] != $user_rule) || ($user['user_giftbag_level'] != $user_giftbag_level)){
                    // 推送
                    try{
                        $this->Jpush(1, (string)$user_id, '角色变更', ['send_type' => 2, 'user_id' => $user_id]);
                    }catch(\Exception $ee){
                        return json(['code' => 100, 'msg' => $ee->getMessage()]);
                    }
                }
                
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => $msg]);
            }
        }
        $province = Db::table('up_area')->where('level', 1)->field('district_id, district')->select();
        $city = Db::table('up_area')->where('pid', $user['user_sheng'])->field('district_id, district')->select();
        $qu = Db::table('up_area')->where('pid', $user['user_shi'])->field('district_id, district')->select();
        $user['user_bo_district_role'] = trim($user['user_bo_district_role'], ',');
        $thRule = Db::table('up_th_rule')->where('rule_status', 1)->field('rule_id, rule_name')->select();
        $this->assign([
            'user' => $user,
            'user_id' => $user_id,
            'province' => $province,
            'city' => $city,
            'qu' => $qu,
            'rule' => $thRule
        ]);
        return $this->fetch('member/appmemberdetail');
    }
    
    /**
     * 设置区域
     * @return mixed|\think\response\Json
     */
    public function setDistrict(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $user_district_id = input('user_district_id');
            $set = [
                'user_district_id' => $user_district_id,
                'user_update_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_u_user')->where('user_id', $user_id)->update($set);
            if($res){
                return json(['code' => 200, 'msg' => '设置成功']);
            }else{
                return json(['code' => 100, 'msg' => '设置失败']);
            }
        }
        // 用户
        $user = Db::table('up_u_user')->where('user_id', $user_id)->field('user_district_id')->find();
        // 区域
        $district = Db::table('up_district')->field('dis_id, dis_name')->select();
        $this->assign([
            'user_id' => $user_id,
            'district' => $district,
            'user' => $user
        ]);
        return $this->fetch('member/setdistrict');
    }
    
    /**
     * 删除用户
     * @return \think\response\Json
     */
    public function memberDel(){
        $user_id = input('id');
        $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_status', 3);
        if($res){
            return json(['code' => 200, 'msg' => '删除成功']);
        }else{
            return json(['code' => 100, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 设置店长
     * @return mixed|\think\response\Json
     */
    public function setShopkeeper(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $user_shop_id = input('user_shop_id');
            $set = [
                'user_is_shopkeeper' => 1,
                'user_shop_id' => $user_shop_id,
                'user_update_time' => date('Y-m-d H:i:s')
            ];
            $res = Db::table('up_u_user')->where('user_id', $user_id)->update($set);
            if($res){
                return json(['code' => 200, 'msg' => '设置成功']);
            }else{
                return json(['code' => 100, 'msg' => '设置失败']);
            }
        }
        // 店铺
        $shop = Db::table('up_shop')->where('s_verify', 2)->where('s_status', 2)->field('s_id, s_com_name')->select();
        $this->assign([
            'user_id' => $user_id,
            'shop' => $shop
        ]);
        return $this->fetch('member/setshopkeeper');
    }
    
    /**
     * 撤销店长
     * @return \think\response\Json
     */
    public function cancelShopkeeper(){
        $user_id = input('id');
        $res = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update(['user_is_shopkeeper' => 3, 'user_shop_id' => null, 'user_district_id' => null]);
        if($res){
            return json(['code' => 200, 'msg' => '撤销成功']);
        }else{
            return json(['code' => 100, 'msg' => '撤销失败']);
        }
    }
    
    /**
     * 撤销店员
     * @return \think\response\Json
     */
    public function cancelShopUser(){
        $user_id = input('id');
        $res = Db::table('up_u_user')
            ->where('user_id', $user_id)
            ->update(['user_is_shopkeeper' => 3, 'user_shop_id' => null, 'user_district_id' => null]);
        if($res){
            return json(['code' => 200, 'msg' => '撤销成功']);
        }else{
            return json(['code' => 100, 'msg' => '撤销失败']);
        }
    }

    /**
     * 开通店铺
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function openStore(){
        $user_id = input('id');
        $store = Db::table('up_bo_giftbag_store')->where('bs_user_id', $user_id)->find();
        if(!$store){
            $bs_id = Db::table('up_bo_giftbag_store')->insertGetId([
                'bs_user_id' => $user_id,
                'bs_register_from' => 2,
                'bs_check_time' => date('Y-m-d H:i:s'),
                'bs_time' => date('Y-m-d H:i:s'),
                'bs_status' => 2
            ]);
            if($bs_id){
                $bs_code = 'G' . str_pad($bs_id, 7, 0, STR_PAD_LEFT);
                $vip_qrcode = $this->getVipQrcode($bs_code);
                $res = Db::table('up_bo_giftbag_store')->update([
                    'bs_id' => $bs_id,
                    'bs_vip_code' => $bs_code,
                    'bs_vip_qrcode' => $vip_qrcode
                ]);
                if($res){
                    return json(['code' => 200, 'msg' => '操作成功']);
                }else{
                    return json(['code' => 100, 'msg' => '系统异常，请稍后重试']);
                }
            }else{
                return json(['code' => 100, 'msg' => '系统异常，请稍后重试']);
            }
        }else{
            return json(['code' => 200, 'msg' => '操作成功']);
        }
    }
    
    /**
     * 用户课程积分
     * @return \think\response\Json
     */
    public function classBalance(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $user_class_balance = input('user_class_balance');
            
            Db::startTrans();
            try{
                // 增加积分
                Db::table('up_u_user')->where('user_id', $user_id)->setInc('user_class_balance', $user_class_balance);
                
                // 入积分表
                $inte = [
                    'ci_user_id' => $user_id,
                    'ci_integral' => $user_class_balance,
                    'ci_type' => 1,
                    'ci_time' => date('Y-m-d H:i:s')
                ];
                Db::table('up_class_integral')->insert($inte);
                
                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            }catch(\Exception $e){
                Db::rollback();
                return json(['code' => 100, 'msg' => $e->getMessage()]);
            }
        }
        $class_balance = Db::table('up_u_user')->where('user_id', $user_id)->value('user_class_balance');
        return $this->fetch('member/classbalance', ['user_id' => $user_id, 'balance' => $class_balance]);
    }
    
    /**
     * 导出
     * @return \think\response\Json
     */
    public function outExcel(){
        set_time_limit(0);
        $user_ids = input('ids');

        $where['user_status'] = ['neq', 3];
        $where['user_private_worker'] = 1;
//            $where['user_private_worker'] = 1;
        if($user_ids == -1){
            $keyword = trim(input('keyword'), ' '); // 用户ID/手机号/姓名/昵称
            $user_gender = input('user_gender'); // 性别   1 男   2 女   3 未知
            $user_sheng = input('user_sheng');
            $user_shi = input('user_shi');
            $user_qu = input('user_qu');
            $user_bo_role = input('user_bo_role'); // 1 普通用户  2 自由创业者  3 团员   4 团队长
            $user_bo_district_role = input('user_bo_district_role'); // 2 县级运营商  3 市级分公司  4 省级子公司
            $start_time = input('start_time'); // 注册开始时间
            $end_time = input('end_time'); // 注册结束时间
            $login_start_time = input('login_start_time'); // 登录开始时间
            $login_end_time = input('login_end_time'); // 登录结束时间
            $user_rule = input('user_rule'); // 1 普通用户  2 特惠商品  3 脖脸皮  2,3特惠商品&脖脸皮
            // 关键字
            if(isset($keyword) && $keyword != ''){
                $where['user_id|user_phone|user_username|user_real_name'] = ['like', '%' . $keyword . '%'];
            }
            // 性别
            if(isset($user_gender) && $user_gender != ''){
                $where['user_gender'] = $user_gender;
            }
            // 省
            if(isset($user_sheng) && $user_sheng != ''){
                $where['user_sheng'] = $user_sheng;
            }
            // 市
            if(isset($user_shi) && $user_shi != ''){
                $where['user_shi'] = $user_shi;
            }
            // 区
            if(isset($user_qu) && $user_qu != ''){
                $where['user_qu'] = $user_qu;
            }
            // 脖脸皮系统等级
            if(isset($user_bo_role) && $user_bo_role != ''){
                $where['user_bo_role'] = $user_bo_role;
            }
            // 脖脸皮地区等级
            if(isset($user_bo_district_role) && $user_bo_district_role != ''){
                $where['user_bo_district_role'] = ['LIKE', '%,' . $user_bo_district_role . ',%'];
            }
            // 类型
            if(isset($user_rule) && $user_rule != ''){
                if($user_rule == 1){
                    $where['user_rule'] = 1;
                }elseif ($user_rule == 2){
                    $where['user_rule'] = [['=', 2], ['=', '2,3'], 'OR'];
                }elseif ($user_rule == 3){
                    $where['user_rule'] = [['=', 3], ['=', '2,3'], 'OR'];
                }else{
                    $where['user_rule'] = '2,3';
                }
            }
            // 注册时间
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['between', [$start_time, $end_time]];
            }
            if(isset($start_time) && $start_time != '' && isset($end_time) && $end_time == ''){
                $where['user_time'] = ['>=', $start_time];
            }
            if(isset($start_time) && $start_time == '' && isset($end_time) && $end_time != ''){
                $where['user_time'] = ['<=', $end_time];
            }
            // 登录时间
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['between', [$login_start_time, $login_end_time]];
            }
            if(isset($login_start_time) && $login_start_time != '' && isset($login_end_time) && $login_end_time == ''){
                $where['user_last_login'] = ['>=', $login_start_time];
            }
            if(isset($login_start_time) && $login_start_time == '' && isset($login_end_time) && $login_end_time != ''){
                $where['user_last_login'] = ['<=', $login_end_time];
            }
        }else{
            if($user_ids == '') return json(['code' => 100, 'msg' => '请选择需要导出的数据']);
            $where['user_id'] = ['IN', $user_ids];
        }

        $list = Db::table('up_u_user')
            ->field([
                'user_id',
                'user_username',
                'user_phone',
                'user_area_str',
                'user_gender',
                'user_time',
                'user_real_name',
                'user_status',
                'user_last_login',
                'user_shop_name',
                'user_address',
                'user_rule',
                'user_total_balance',
                'user_recharge_balance',
                'user_big_total_balance',
                'user_big_balance',
                'user_bo_total_balance',
                'user_bo_balance',
                'user_bo_first_balance',
                'user_bo_huo_balance',
                'user_bo_other_balance',
                'user_invite',
                'user_bank_username',
                'user_bank_name',
                'user_bankcard_code',
                'user_from',
                'user_bo_district_role',
                'user_bo_role',
                'user_up_tz_code',
                'user_ty_code',
                'user_up_up_tz_code',
                'user_tz_code'
            ])
            ->where($where)
            ->select();
        
        foreach($list as $k => $v){
            // 手机号
            $list[$k]['user_phone'] = "\t" . $v['user_phone'] . "\t";
            // 性别
            switch($v['user_gender']){
                case 1:
                    $list[$k]['user_gender'] = '男';
                    break;
                case 2:
                    $list[$k]['user_gender'] = '女';
                    break;
                case 3:
                    $list[$k]['user_gender'] = '未知';
                    break;
            }
            // 类型
            switch($v['user_rule']){
                case 1:
                    $list[$k]['user_rule'] = '普通用户';
                    break;
                case 2:
                    $list[$k]['user_rule'] = '特惠商品用户';
                    break;
                case 3:
                    $list[$k]['user_rule'] = '脖脸皮用户';
                    break;
                case '2,3':
                    $list[$k]['user_rule'] = '特惠商品&脖脸皮用户';
                    break;
            }
            // 脖脸皮系统身份
            if($v['user_bo_role'] == 1){
                $list[$k]['user_bo_role'] = '普通用户';
            }elseif ($v['user_bo_role'] == 2){
                $list[$k]['user_bo_role'] = '自已创业者';
            }elseif($v['user_bo_role'] == 3){
                $list[$k]['user_bo_role'] = '团员';
            }else{
                $list[$k]['user_bo_role'] = '团队长';
            }
            // 脖脸皮代理身份
            if($v['user_bo_district_role'] == '1'){
                $district_role = '普通用户';
                $list[$k]['district_role'] = $district_role;
            }else{
                $district_role = '';
                if(strpos($v['user_bo_district_role'], ',2,') !== false) $district_role .= '县级运营商';
                if(strpos($v['user_bo_district_role'], ',3,') !== false) $district_role .= '，市级分公司';
                if(strpos($v['user_bo_district_role'], ',4,') !== false) $district_role .= '，省级子公司';
                $list[$k]['district_role'] = trim($district_role, '，');
            }
            // 注册来源
            $list[$k]['user_from'] = $v['user_from'] == 1 ? 'APP注册' : '后台注册';
            // 状态
            $list[$k]['user_status'] = $v['user_status'] == 1 ? '正常' : '冻结';
            // 银行卡
            $list[$k]['user_bankcard_code'] = "\t" . $v['user_bankcard_code'] . "\t";
            // 团员、团队长编号
            if($v['user_bo_role'] == 3){
                $tyCode = $v['user_up_tz_code'] . '_' . $v['user_ty_code'];
                $tzCode = '/';
            }elseif($v['user_bo_role'] == 4){
                $tyCode = '/';
                $tzCode = $v['user_tz_code'];
                $tzCode .= $v['user_up_tz_code'] == -1 ? '' : '_' . $v['user_up_tz_code'];
                $tzCode .= $v['user_up_up_tz_code'] == -1 ? '' : '_' . $v['user_up_up_tz_code'];
            }else{
                $tyCode = '/';
                $tzCode = '/';
            }
            $list[$k]['tyCode'] = $tyCode;
            $list[$k]['tzCode'] = $tzCode;
        }

        $cellname = [
            ['user_username', '昵称', 15, 'LEFT'],
            ['user_phone', '手机号', 18, 'LEFT'],
            ['user_real_name', '姓名', 15, 'LEFT'],
            ['user_from', '注册途径', 12, 'LEFT'],
            ['user_rule', '用户类型', 18, 'LEFT'],
            ['user_bo_role', '脖脸皮系统身份', 18, 'LEFT'],
            ['tzCode', '团队长编号', 12, 'LEFT'],
            ['tyCode', '团员编号', 12, 'LEFT'],
            ['district_role', '脖脸皮代理身份', 18, 'LEFT'],
            ['user_gender', '性别', 10, 'LEFT'],
            ['user_status', '状态', 10, 'LEFT'],
            ['user_area_str', '地区', 40, 'LEFT'],
            ['user_address', '详细地址', 30, 'LEFT'],
            ['user_time', '注册时间', 18, 'LEFT'],
            ['user_last_login', '最后登录时间', 18, 'LEFT'],
            ['user_invite', '邀请码', 15, 'LEFT'],
            ['user_shop_name', '店铺名称', 20, 'LEFT'],
            ['user_total_balance', '特惠商品总积分', 15, 'LEFT'],
            ['user_recharge_balance', '特惠商品可用积分', 15, 'LEFT'],
            ['user_big_total_balance', '家大业大总积分', 15, 'LEFT'],
            ['user_big_balance', '家大业大可用积分', 15, 'LEFT'],
            ['user_bo_total_balance', '脖脸皮总积分', 15, 'LEFT'],
            ['user_bo_balance', '脖脸皮可用积分', 15, 'LEFT'],
            ['user_bo_first_balance', '脖脸皮首批款', 15, 'LEFT'],
            ['user_bo_huo_balance', '脖脸皮补货款', 15, 'LEFT'],
            ['user_bo_other_balance', '脖脸皮其它款', 15, 'LEFT'],
            ['user_bank_name', '开户行', 12, 'LEFT'],
            ['user_bank_username', '开户名', 12, 'LEFT'],
            ['user_bankcard_code', '卡号', 22, 'LEFT']
        ];
        
        $res = exportExcelZhy('用户表', 'Member', $cellname, $list);
        return json($res);
    }

    /**
     * 用户私人订制库存列表
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function privateStock(){
        if(request()->isAjax()){
            $where['stock_user_id'] = session('stock_user_id');
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::name('private_stock')
                ->join('up_private_setmeal', 'stock_ps_id = ps_id', 'LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::name('private_stock')
                ->join('up_private_setmeal', 'stock_ps_id = ps_id', 'LEFT')
                ->where($where)
                ->field('stock_id, stock_user_id, stock_number, ps_name, ps_image')
                ->page($NowPage,$limits)
                ->order('stock_id desc')
                ->select();

            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $user_id = input('user_id');
        if($user_id) session('stock_user_id', $user_id);
        return $this->fetch();
    }

    /**
     * 添加私人订制库存
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function privateStockAdd(){
        if(Request::instance()->isPost()){
            $ps_id = input('ps_id');
            $ps_number = input('ps_number');

            $has = Db::table('up_private_stock')
                ->where(['stock_user_id' => session('stock_user_id'), 'stock_ps_id' => $ps_id])
                ->find();
            if($has){
                $res = Db::table('up_private_stock')
                    ->where('stock_id', $has['stock_id'])
                    ->inc('stock_number', $ps_number)
                    ->update();
            }else{
                $res = Db::table('up_private_stock')
                    ->insert([
                        'stock_user_id' => session('stock_user_id'),
                        'stock_ps_id' => $ps_id,
                        'stock_number' => $ps_number
                    ]);
            }
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '系统异常，请稍后重试']);
            }
        }
        $setMeal = Db::table('up_private_setmeal')->where('ps_status', 1)->field('ps_id, ps_name')->select();
        return $this->fetch('', ['setMeal' => $setMeal]);
    }

    /**
     * 编辑私人订制库存
     * @return mixed|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function privateStockEdit(){
        $stock_id = input('stock_id');
        $stock = Db::table('up_private_stock')->where('stock_id', $stock_id)->find();
        if(Request::instance()->isPost()){
            $type = input('type'); // 1 增加   2 减少
            $number = input('number');

            if($type == 2){
                if($number > $stock['stock_number']){
                    return json(['code' => 100, 'msg' => '减少数量不可低于库存']);
                }
                $s_number = $stock['stock_number'] - $number;
            }else{
                $s_number = $stock['stock_number'] + $number;
            }

            $res = Db::table('up_private_stock')->where('stock_id', $stock_id)->setField('stock_number', $s_number);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '系统异常，请稍后重试']);
            }
        }
        return $this->fetch('', ['stock' => $stock]);
    }

    /**
     * 批量修改福利权限
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function batchUpdateRule(){
        $userIds = input('ids');
        if(Request::instance()->isPost()){
            $rule_id = input('rule_id');

            $update = [
                'user_th_rule' => $rule_id
            ];
            $res = Db::table('up_u_user')->where('user_id', 'IN', $userIds)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '修改成功']);
            }else{
                return json(['code' => 100, 'msg' => '修改失败']);
            }
        }
        $rule = Db::table('up_th_rule')->field('rule_id, rule_name')->select();
        return $this->fetch('', ['userIds' => $userIds, 'rule' => $rule]);
    }

    /**
     * 解除绑定礼包上级
     * @return \think\response\Json
     */
    public function relieveUp(){
        $user_id = input('id');
        $giftbag_invite_other = Db::table('up_u_user')->where('user_id', $user_id)->value('user_giftbag_invite_other');
        if(!$giftbag_invite_other){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            $res = Db::table('up_u_user')->where('user_id', $user_id)->setField('user_giftbag_invite_other', 0);
            if($res){
                return json(['code' => 200, 'msg' => '操作成功']);
            }else{
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
    }

    /**
     * 私人订制库存----作废
     * @return mixed|\think\response\Json
     */
    public function privateStock1(){
        $user_id = input('user_id');
        if(Request::instance()->isPost()){
            $user_private_stock = input('user_private_stock');
            $res = Db::table('up_u_user')
                ->update(['user_id' => $user_id, 'user_private_stock' => $user_private_stock]);
            if($res){
                return json(['code' => 200, 'msg' => '设置成功']);
            }else{
                return json(['code' => 100, 'msg' => '设置失败']);
            }
        }
        $stock = Db::table('up_u_user')->where('user_id', $user_id)->value('user_private_stock');
        $this->assign([
            'user_id' => $user_id,
            'stock' => $stock
        ]);
        return $this->fetch('member/privatestock');
    }

    /**
     * 编辑后台添加的用户---作废
     * @return mixed
     */
    public function memberDetail(){
        $user_id = input('user_id');
        $info = Db::name('u_user')->where('user_id', $user_id)->find();
        if(Request::instance()->isPost()){
//            $id = input('user_id');
            $user_username = trim(input('user_username'), ' ');
            $user_phone = input('user_phone');
            $user_image = input('user_image');
            $user_gender = input('user_gender');
            $user_status = input('user_status');
            $user_index = input('user_index');
            $user_submit = input('user_submit');
            $user_password = input('user_password');
            if(!$user_username || !$user_phone || !$user_username){
                return json(['code' => 100, 'msg' => '有未填项']);
            }
            if(!preg_match("/^1[123456789]\d{9}$/", $user_phone)){
                return json(['code' => 100, 'msg' => '请填写正确的手机号']);
            }
            $update = [
                'user_username' => $user_username,
                'user_phone' => $user_phone,
                'user_image' => $user_image,
                'user_gender' => $user_gender,
                'user_status' => $user_status,
                'user_index' => $user_index,
                'user_submit' => $user_submit,
                'user_update_time' => date('Y-m-d H:i:s')
            ];
            if($user_password){
                $update['user_password'] = md5($user_password);
            }
            $data = Db::table('up_u_user')->where('user_id', $user_id)->find();
            if($data['user_phone'] != $user_phone){
                $have = Db::table('up_u_user')
                    ->where('user_phone', $user_phone)
                    ->find();
                if($have){
                    return json(['code' => 100, 'msg' => '此手机号码已经有了']);
                }
            }
            $res = Db::table('up_u_user')->where('user_id', $user_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '编辑成功']);
            }else{
                return json(['code' => 100, 'msg' => '编辑失败']);
            }
        }

        $this->assign('info', $info);
        $this->assign('user_id', $user_id);
        return $this->fetch('member/memberdetail');
    }
}